package com.winning.gjhlht.ihe.hl7ClientService.data.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cownew.ctk.common.RandomGUID;
import com.framework.helper.ServerSQLExecutorUtils;
import com.framework.server.db.bean.PageBean;
import com.framework.server.db.bean.PageQueryBean;
import com.framework.server.manager.SQLConfigLoader;
import com.winning.common.data.service.PlatBasicDataService;
import com.winning.gjhlht.ihe.cdaService.service.IBaseCDACreaterServiceInter;
import com.winning.gjhlht.ihe.common.IHEConstans;
import com.winning.gjhlht.ihe.hl7ClientService.data.dao.inter.IHEDataDaoInter;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 类名称：IHEJkdaDataService
 * 类描述：   健康档案互联互通服务
 * 创建人：zhaqiang
 * 创建时间：2017-3-1 上午10:02:46
 * 修改人：zhaqiang
 * 修改时间：2017-3-1 上午10:02:46
 * 修改备注：
 */
@Service(value = "com.winning.gjhlht.ihe.hl7ClientService.data.service.IHEJkdaDataService")
public class IHEJkdaDataService extends IHEBaseDataService {
    private static Logger LOGGER = Logger.getLogger("pbsLoger");

    //张家港健康档案服务ID
    private static final String ZJG_JKDA_SERVICE_ID = "JKDA_ZJG_TEMP_002";

    @Autowired
    private PlatBasicDataService platBasicDataService = null;

    @Autowired
    private IHEDataDaoInter iheDataDao = null;

    @Autowired
    private IBaseCDACreaterServiceInter baseCDACreaterService = null;

    /**
     * 获取健康档案上传结果统计信息
     * 方法名称: getJKDAZCJGCount
     *
     * @param
     * @return JSONObject  返回类型说明<br/>
     * @throws <br/>
     * @author zq@winning.com.cn<br/>
     * 创建时间：2017-2-7/上午10:22:43<br/>
     */
    public JSONObject getJKDAZCJGCount(Map<String, Object> param) {
        JSONObject result = new JSONObject();

        try {
            String sql = SQLConfigLoader.getSQLByID("IHE_Client_CountJKDA");

            //			String sql = "with a as (select * from IHE_CDA_DOC_BUFFER where 1=1 ";
            //
            //			//根据参数拼接条件查询语句
            //			if(param.containsKey("JGBM"))
            //			{
            //				sql += " and OID = '"+param.get("JGBM").toString()+"'";
            //			}
            //
            //			if(param.containsKey("ZJHM"))
            //			{
            //				sql += " and IdentityId = '"+param.get("ZJHM")+"'";
            //			}
            //
            //			if(param.containsKey("startDate"))
            //			{
            //				sql += " and CreateTime > to_date('"+param.get("startDate")+"','YYYY-MM-DD')";
            //			}
            //
            //			if(param.containsKey("endDate"))
            //			{
            //				sql += " and CreateTime < to_date('"+param.get("endDate")+"','YYYY-MM-DD')";
            //			}
            //
            //			sql += " ) ";
            //
            //			sql += "select (select count(1) from a )  as ZSL," +
            //					"(select count(1) from a where a.RESPONSESTATUS = 'AA') AS SCCG ," +
            //					"(select count(1) from a where a.RESPONSESTATUS = 'AE') as SCSB ,"+
            //				    "(select count(1) from a where a.RESPONSESTATUS = 'WSC') as WSC , " +
            //				    "(select count(1) from a where YZJG = 'AE') as YZSB ," +
            //				    "(select count(1) from a where YZJG = 'AA') as YZCG ," +
            //				    "(select count(1) from a where ISAUDIT = 'YES')  as SJXX," +
            //				    "(select count(1) from a where ISAUDIT = 'NO' )  as SJWTIJ from a";

            LOGGER.info("--> 处理后的查询简单档案统计SQL语句：" + sql);

            //数据源
            String dbDataSourceID = getDBDataSouorceID(ZJG_JKDA_SERVICE_ID);

            LOGGER.info("--> 查询健康档案统计数据源：" + dbDataSourceID);

            result = iheDataDao.executSQLForJSONObject(sql, null, dbDataSourceID);

            if (result == null) {
                result = new JSONObject();

                result.put("ZSL", 0);
                result.put("SCCG", 0);
                result.put("SCSB", 0);
                result.put("WSC", 0);
                result.put("YZSB", 0);
                result.put("YZCG", 0);
                result.put("SJXX", 0);
                result.put("SJWTIJ", 0);
            }

            result.put("XCZXSJ", getTimeByTrigger(ZJG_JKDA_SERVICE_ID));

            result.put("SJSJ", getTimeByTrigger(ZJG_JKDA_SERVICE_ID));

            LOGGER.info("--> 查询健康档案统计结果:" + result.toString());
        } catch (Exception e) {
            e.printStackTrace();

            LOGGER.error(e, e.fillInStackTrace());
        }
        return result;
    }

    /**
     * 获取个人健康档案注册结果详细信息
     * 方法名称: getJKDAZCJGInfo
     *
     * @param
     * @return JSONObject  返回类型说明<br/>
     * @throws <br/>
     * @author zq@winning.com.cn<br/>
     * 创建时间：2017-2-7/下午1:06:30<br/>
     */
    public JSONObject getJKDAZCJGInfo(int pageSize, int pageNumber, Map<String, Object> param) {

        PageQueryBean pqb = null;
        JSONObject json = new JSONObject();

        try {

            String sql = SQLConfigLoader.getSQLByID("IHE_Client_JKDAInfo");

            //数据源
            String dbDataSourceID = getDBDataSouorceID(ZJG_JKDA_SERVICE_ID);

            //根据参数拼接条件查询语句
            if (param.containsKey("WDLX")) {
                sql += " and WDLX = '" + param.get("WDLX") + "'";
            }
            if (param.containsKey("JGBM")) {
                sql += " and OID = '" + param.get("JGBM").toString() + "'";
            }

            if (param.containsKey("ZJHM")) {
                sql += " and IdentityId = '" + param.get("ZJHM") + "'";
            }

            if (param.containsKey("startDate")) {
                sql += " and CreateTime > to_date('" + param.get("startDate") + "','YYYY-MM-DD')";
            }

            if (param.containsKey("endDate")) {
                sql += " and CreateTime < to_date('" + param.get("endDate") + "','YYYY-MM-DD')";
            }

            if (param.containsKey("SCJG")) {

                String scjg = param.get("SCJG").toString();

                String[] strList = scjg.split("_");

                if (strList != null && strList.length == 2) {
                    if (strList[0].equals("YZ")) {
                        sql += " and YZJG = '" + strList[1] + "'";
                    } else if (strList[0].equals("SC")) {
                        sql += " and RESPONSESTATUS = '" + strList[1] + "'";
                    }
                }

            }

            //做分页处理
            PageBean pageBean = new PageBean();

            pageBean.setPageNum(pageNumber);

            //必须要填的
            pageBean.setPageSize(pageSize);

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");

            LOGGER.info("--> 开始执行SQL 开始时间：" + formatter.format(new Date().getTime()));

            pqb = iheDataDao.executeSQLByPage(pageBean, sql, "", dbDataSourceID);

            LOGGER.info("--> 结束执行SQL 结束时间：" + formatter.format(new Date().getTime()));

            if (pqb.getDataSet() != null) {
                //数据库查询结果集采用XML结构返回
                String resultXML = pqb.getDataSet().toString();

                JSONArray array = paraseXMLToJSONArray(resultXML);

                json.put("rows", array);
                json.put("total", pqb.getPageBean().getRecordCount());
            }

            return json;
        } catch (Exception e) {
            e.printStackTrace();

            LOGGER.error(e, e.fillInStackTrace());
        }

        return null;
    }

    /**
     * 上传一份CDA文档
     * 方法名称: uploadCDAFile
     *
     * @param
     * @return boolean  返回类型说明<br/>
     * @throws <br/>
     * @author zq@winning.com.cn<br/>
     * 创建时间：2017-2-9/下午2:10:07<br/>
     */
    public JSONObject uploadCDAFile(String ID) {

        JSONObject json = new JSONObject();
        try {

            String tjSQL = " AND ID = '" + ID + "'";

            boolean tag = uploadHlhtService(tjSQL, ZJG_JKDA_SERVICE_ID, platBasicDataService, iheDataDao);

            if (tag) {
                String sql = "SELECT YZJG,YZJGSM,RESPONSESTATUS,RESPONSEDETAIL FROM IHE_CDA_DOC_BUFFER WHERE ID = '"
                        + ID + "'";

                //数据源
                String dbDataSourceID = getDBDataSouorceID(ZJG_JKDA_SERVICE_ID);

                JSONObject result = iheDataDao.executSQLForJSONObject(sql, null, dbDataSourceID);

                if (result != null) {
                    if (result.getString("YZJG").equals("AA")) {

                        String status = result.getString("RESPONSESTATUS").toString().trim();

                        if (status.equals("AA")) {
                            json.put("RS", "TRUE");
                        } else if (status.equals("AE")) {
                            json.put("RS", "FALSE");
                            json.put("INFO", "注册出错," + result.getString("RESPONSEDETAIL"));
                        } else {
                            json.put("RS", "FALSE");
                            json.put("INFO", "注册流程出错!");
                        }
                    } else {
                        json.put("RS", "FALSE");
                        json.put("INFO", "验证CDA格式出错," + result.getString("YZJGSM"));
                    }
                } else {
                    json.put("RS", "FALSE");
                    json.put("INFO", "注册结果未保存到本地系统!");
                }
            } else {
                json.put("RS", "FALSE");
                json.put("INFO", "注册流程出错!");
            }

        } catch (Exception e) {
            LOGGER.error(e, e.fillInStackTrace());

            json.put("RS", "FALSE");
            json.put("INFO", e.fillInStackTrace());

        }

        return json;
    }

    /**
     * 分页查询注册用户信息
     * 方法名称: pageQueryRegisterPersion
     *
     * @param
     * @return JSONObject  返回类型说明<br/>
     * @throws <br/>
     * @author zq@winning.com.cn<br/>
     * 创建时间：2017-2-8/下午2:06:04<br/>
     */
    public JSONObject pageQueryRegisterPersion(Map<String, Object> param, int pageNumber, int pageSize) {
        JSONObject result = new JSONObject();

        try {
            //查询SQL
            String sql = "SELECT YLJGDM ,c.JGMC, GJPTBSH , ZJHM ,CONVERT(varchar(100),ZCRQ,23) AS ZCRQ, XM ,JBXXBSH,ROW_NUMBER() OVER (ORDER BY ZCRQ DESC) AS RN ,(SELECT COUNT(1) FROM IHE_CDA_DOC_BUFFER WHERE IDENTITYID = ZJHM ";

            //			//根据参数拼接SQL
            //			if(param.containsKey("WDLX"))
            //			{
            //				sql += " AND WDLX = '"+param.get("WDLX")+"'";
            //			}

            sql += " ) AS WDSL FROM IHE_GR_JBXX_LOG b left join SYS_ZCJG c on b.YLJGDM = c.JGBM WHERE ZCJG = 'AA' ";

            if (param.containsKey("ZJHM")) {
                sql += " AND ZJHM = '" + param.get("ZJHM") + "'";
            }
            if (param.containsKey("JGBM")) {
                sql += " AND YLJGDM = '" + param.get("JGBM") + "'";
            }
            if (param.containsKey("XM")) {
                sql += " AND XM like '%" + param.get("XM") + "%'";
            }

            String totalSQL = "SELECT COUNT(1)  AS TOTALCOUNT FROM (" + sql + ") a ";

            //总记录数
            int total = 0;

            LOGGER.info("-->查询个人注册信息分页总记录数查询SQL： " + totalSQL);

            String dbDataSourceID = getDBDataSouorceID(ZJG_JKDA_SERVICE_ID);

            total = iheDataDao.queryTotalDataCount(totalSQL, "TOTALCOUNT", dbDataSourceID);

            LOGGER.info("-->个人注册信息总记录数:" + total);

            String querySQL = "select * from (" + sql + ") a where a.RN between ? and ?  order by a.ZCRQ desc";

            LOGGER.info("-->分页查询个人注册信息的SQL：" + querySQL);
            LOGGER.info("-->分页查询个人注册信息pageNumber:" + pageNumber);
            LOGGER.info("-->分页查询个人注册信息pageSize:" + pageSize);

            List<JSONObject> list = iheDataDao.executeSQLForJSONArrayList(querySQL,
                    new Object[]{(pageNumber - 1) * pageSize, pageSize * pageNumber}, dbDataSourceID);

            result.put("rows", list);
            result.put("total", total);

            return result;

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e, e.fillInStackTrace());
        }

        return result;
    }

    /**
     * 获取个人的CDA文档信息
     * 方法名称: getPersionCDAInfo
     *
     * @param
     * @return JSONObject  返回类型说明<br/>
     * @throws <br/>
     * @author zq@winning.com.cn<br/>
     * 创建时间：2017-2-9/下午1:22:53<br/>
     */
    public JSONObject getPersionCDAInfo(String ID) {
        JSONObject result = new JSONObject();

        try {
            String sql = "SELECT ID,TITLE, WDLX ,"
                    + "CASE RESPONSESTATUS WHEN 'AA' THEN '上传成功' WHEN 'AE' THEN '上传失败' WHEN 'WSC' THEN '未上传' END AS RESPONSESTATUS,"
                    + "CONVERT(varchar(100),CREATETIME,23) AS CREATETIME ,"
                    + "CASE YZJG WHEN 'AA' THEN '验证成功' WHEN 'AE' THEN '验证失败' END AS YZJG  FROM IHE_CDA_DOC_BUFFER WHERE SOURCEPATIENTID = ?  order by CREATETIME desc";

            LOGGER.info("-->查询个人健康档案记录SQL:" + sql);

            //获取数据源
            String dbDataSourceID = getDBDataSouorceID(ZJG_JKDA_SERVICE_ID);

            List<JSONObject> list = iheDataDao.executeSQLForJSONArrayList(sql, new Object[]{ID}, dbDataSourceID);

            result.put("DATA", list);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e, e.fillInStackTrace());
        }

        return result;
    }

    /**
     * 生成一个患者对应文档类型的所有CDA信息
     * 方法名称: createAllCDAByPersion
     *
     * @param
     * @return JSONObject  返回类型说明<br/>
     * @throws <br/>
     * @author zhaqiang@winning.com.cn<br/>
     * 创建时间：2017-3-10/上午9:02:54<br/>
     */
    public JSONObject createAllCDAByPersion(String ID, String WDLX) {
        JSONObject result = new JSONObject();

        try {
            //数据源
            String dbDataSourceID = getDBDataSouorceID(ZJG_JKDA_SERVICE_ID);

            //查询CDA信息SQL语句
            String basicSQL = "SELECT JBXXBSH,GJPTBSH,ZJHM,YLJGDM,XM,CONVERT(varchar(100),ZCRQ,23) AS IHE_GR_JBXX_LOG_TBRQ FROM IHE_GR_JBXX_LOG WHERE ZCJG = 'AA' AND JBXXBSH = ?";

            LOGGER.info("-->查询个人信息:" + basicSQL);
            LOGGER.info("-->个人基本信息标识号:" + ID);

            //根据ID查询需要生成CDA文档的信息
            List<HashMap<String, Object>> list = iheDataDao.executeSQLByDataSourseID(basicSQL, new Object[]{ID},
                    dbDataSourceID);

            //填充所有信息, 并发送请求
            if (list != null && list.size() > 0) {

                //获取患者详细信息
                Map<String, Object> map = list.get(0);

                if (map != null) {
                    //个人基本标识号
                    String grjbbsh = map.get(IHEConstans.KEY_JBXX_REGISTER_GRJBXXBSH).toString();

                    //身份证号
                    String zjhm = map.get(IHEConstans.KEY_PERSION_REGISTER_ZJHM).toString();

                    //机构代码
                    String jgbm = map.get(IHEConstans.KEY_PERSION_REGISTER_YLJGDM).toString();

                    //国家平台唯一标识号
                    String gjptbsh = map.get(IHEConstans.KEY_JBXX_REGISTER_GJPTBSH).toString();

                    //患者姓名
                    String xm = map.get(IHEConstans.KEY_PERSION_REGISTER_XM).toString();

                    String title = getCdaTitleByWDLX(WDLX);

                    //根据文档类型获取cda模板文件名称
                    String cdaTempFileName = getCdaTempFileByWDLX(WDLX);

                    //根据文档类型获取CDA信息查询语句
                    String sql = getQueryCDAInfoSQLByWDLX(WDLX);

                    //非空判断
                    if (cdaTempFileName.equals("") || cdaTempFileName == null || sql == null || sql.equals("")) {
                        result.put("RESULT", "FAILD");
                        result.put("MSG", "未找到对应的文档类型");
                        return result;
                    }

                    Object[] param = null;

                    //个人基本健康信息需要两个参数
                    if (WDLX.equals("01")) {
                        param = new Object[]{grjbbsh, grjbbsh};
                    } else {
                        param = new Object[]{grjbbsh};
                    }

                    //获取生成的CDA文档信息
                    List<HashMap<String, Object>> cdaList = baseCDACreaterService.createCDADocumentService(xm, "",
                            cdaTempFileName, sql, param, dbDataSourceID);

                    if (cdaList != null && cdaList.size() > 0) {

                        int index = 1;

                        for (HashMap<String, Object> cdaDocumentContenValue : cdaList) {

                            LOGGER.info(" --> 开始处理第 " + index + " 份CDA文档");

                            //将生成的CDA文档和其他基本信息保存到：CDA文档缓存表<IHE_CDA_DOC_BUFFER>
                            if (cdaDocumentContenValue != null) {
                                String cdaDocumentStr = cdaDocumentContenValue.get("cdaDocument").toString();

                                if (cdaDocumentStr == null || cdaDocumentStr.equals("")) {
                                    result.put("RESULT", "FAILD");
                                    result.put("MSG", "第" + index + "份CDA文档为空");
                                    return result;
                                }

                                //获取个人基本信息
                                HashMap<String, Object> jbxxMap = queryGRJBXX(grjbbsh, dbDataSourceID);

                                //全球唯一ID
                                String requestID = new RandomGUID().toString();

                                if (jbxxMap != null) {
                                    HashMap<String, Object> paramCDA = new HashMap<String, Object>();

                                    paramCDA.put("Id", requestID);

                                    paramCDA.put("SourcePatientID", gjptbsh);

                                    paramCDA.put("SourcePatientName", xm);

                                    paramCDA.put("TITLE", title);

                                    paramCDA.put("IdentityId", zjhm);

                                    paramCDA.put("UniqueId", requestID);

                                    paramCDA.put("DocumentId", new RandomGUID().toString());

                                    paramCDA.put("WDLX", WDLX);

                                    //验证结果
                                    if (cdaDocumentContenValue.containsKey("YZJG")) {
                                        paramCDA.put("YZJG", cdaDocumentContenValue.get("YZJG").toString());

                                        if (cdaDocumentContenValue.containsKey("YZJGSM")) {
                                            paramCDA.put("YZJGSM", cdaDocumentContenValue.get("YZJGSM").toString());

                                            if (cdaDocumentContenValue.get("YZJG").equals("AE")) {
                                                result.put("RESULT", "FAILD");
                                                result.put("MSG", "第" + index + "份CDA文档格式验证失败，失败原因:"
                                                        + cdaDocumentContenValue.get("YZJGSM").toString());
                                                return result;
                                            }
                                        }

                                    }

                                    //转base64编码
                                    String base64Str = getBASE64(cdaDocumentStr);
                                    if (base64Str == null || base64Str.equals("")) {
                                        result.put("RESULT", "FAILD");
                                        result.put("MSG", "第" + index + "份CDA文档生成Base64编码失败");

                                        return result;
                                    }

                                    paramCDA.put("CONTENT", base64Str);
                                    paramCDA.put("xmlContent", cdaDocumentStr);

                                    //循环遍历查询出的个人新，并将其放入CDA缓存map中
                                    for (String key : jbxxMap.keySet()) {
                                        paramCDA.put(key, jbxxMap.get(key));
                                    }

                                    //填充CDA关键信息
                                    /**
                                     * 许多信息并不清楚本地库对应表结构和字段，待完善
                                     */

                                    //将cda信息保存到数据库
                                    int returnRs = saveCDADOCBUFFER(paramCDA, dbDataSourceID);

                                    if (returnRs != -1) {
                                        LOGGER.info("--> CDA信息到表 IHE_CDA_DOC_BUFFER 成功");

                                    } else {
                                        LOGGER.info("--> CDA信息到表 IHE_CDA_DOC_BUFFER 失败");

                                        result.put("RESULT", "FAILD");
                                        result.put("MSG", "第" + index + "份CDA信息存入缓存表失败");
                                        return result;
                                    }

                                }
                            }

                            index++;
                        }

                        result.put("RESULT", "OK");
                        result.put("MSG", "共生成了" + (index - 1) + "份CDA文档");
                        return result;
                    } else {
                        result.put("RESULT", "FAILD");
                        result.put("MSG", "没有该患者的" + title + "信息");
                    }
                }
            }

        } catch (Exception e) {
            LOGGER.error(e, e.fillInStackTrace());
            result.put("RESULT", "FAILD");
            result.put("MSG", "系统错误");
        }

        return result;
    }

    /**
     * 生成一份CDA文档
     * 方法名称: createCDAByPersion
     *
     * @param
     * @return JSONObject  返回类型说明<br/>
     * @throws <br/>
     * @author lenovo@winning.com.cn<br/>
     * 创建时间：2017-2-9/上午8:29:48<br/>
     */
    public JSONObject createCDAByPersion(String ID, String WDLX) {
        JSONObject result = new JSONObject();

        try {
            //数据源
            String dbDataSourceID = getDBDataSouorceID(ZJG_JKDA_SERVICE_ID);

            //查询CDA信息SQL语句
            String basicSQL = "SELECT JBXXBSH,GJPTBSH,ZJHM,YLJGDM,XM,CONVERT(varchar(100),ZCRQ,23) AS IHE_GR_JBXX_LOG_TBRQ FROM IHE_GR_JBXX_LOG WHERE ZCJG = 'AA' AND JBXXBSH = ?";

            LOGGER.info("-->查询个人信息:" + basicSQL);
            LOGGER.info("-->个人基本信息标识号:" + ID);

            //根据ID查询需要生成CDA文档的信息
            List<HashMap<String, Object>> list = iheDataDao.executeSQLByDataSourseID(basicSQL, new Object[]{ID},
                    dbDataSourceID);

            //填充所有信息, 并发送请求
            if (list != null && list.size() > 0) {
                Map<String, Object> map = list.get(0);

                if (map != null) {
                    //个人基本标识号
                    String grjbbsh = map.get(IHEConstans.KEY_JBXX_REGISTER_GRJBXXBSH).toString();

                    //身份证号
                    String zjhm = map.get(IHEConstans.KEY_PERSION_REGISTER_ZJHM).toString();

                    //机构代码
                    String jgbm = map.get(IHEConstans.KEY_PERSION_REGISTER_YLJGDM).toString();

                    //国家平台唯一标识号
                    String gjptbsh = map.get(IHEConstans.KEY_JBXX_REGISTER_GJPTBSH).toString();

                    //患者姓名
                    String xm = map.get(IHEConstans.KEY_PERSION_REGISTER_XM).toString();

                    //全球唯一ID
                    String requestID = new RandomGUID().toString();

                    String title = getCdaTitleByWDLX(WDLX);

                    //根据文档类型获取cda模板文件名称
                    String cdaTempFileName = getCdaTempFileByWDLX(WDLX);

                    //根据文档类型获取CDA信息查询语句
                    String sql = getQueryCDAInfoSQLByWDLX(WDLX);

                    //非空判断
                    if (cdaTempFileName.equals("") || cdaTempFileName == null || sql == null || sql.equals("")) {
                        result.put("RESULT", "FAILD");
                        result.put("MSG", "未找到对应的文档类型");
                        return result;
                    }

                    Object[] param = null;

                    //个人基本健康信息需要两个参数
                    if (WDLX.equals("01")) {
                        param = new Object[]{grjbbsh, grjbbsh};
                    } else {
                        param = new Object[]{grjbbsh};
                    }

                    //根据提供的一个患者的SQL，查询患者的健康档案信息，再根据CDA模板生成标准的CDA文档
                    HashMap<String, Object> cdaDocumentContenValue = baseCDACreaterService
                            .createOneCDADocumentService(xm, requestID, cdaTempFileName, sql, param, dbDataSourceID);

                    //3、将生成的CDA文档和其他基本信息保存到：CDA文档缓存表<IHE_CDA_DOC_BUFFER>
                    if (cdaDocumentContenValue != null) {

                        String cdaDocumentStr = cdaDocumentContenValue.get("cdaDocument").toString();

                        if (cdaDocumentStr == null || cdaDocumentStr.equals("")) {
                            LOGGER.info(" --> 创建CDA的文档为空 ，无法写入数据库");

                            result.put("RESULT", "FAILD");
                            result.put("MSG", "生成CDA文档失败失败");
                            return result;
                        }

                        //获取个人基本信息
                        HashMap<String, Object> jbxxMap = queryGRJBXX(grjbbsh, dbDataSourceID);

                        if (jbxxMap != null) {
                            HashMap<String, Object> paramCDA = new HashMap<String, Object>();

                            paramCDA.put("Id", requestID);

                            paramCDA.put("SourcePatientID", gjptbsh);

                            paramCDA.put("SourcePatientName", xm);

                            paramCDA.put("TITLE", title);

                            paramCDA.put("IdentityId", zjhm);

                            paramCDA.put("UniqueId", requestID);

                            paramCDA.put("DocumentId", new RandomGUID().toString());

                            paramCDA.put("WDLX", WDLX);

                            //验证结果
                            if (cdaDocumentContenValue.containsKey("YZJG")) {
                                paramCDA.put("YZJG", cdaDocumentContenValue.get("YZJG").toString());

                                if (cdaDocumentContenValue.containsKey("YZJGSM")) {
                                    paramCDA.put("YZJGSM", cdaDocumentContenValue.get("YZJGSM").toString());

                                    if (cdaDocumentContenValue.get("YZJG").equals("AE")) {
                                        result.put("RESULT", "FAILD");
                                        result.put("MSG",
                                                "验证CDA文档格式失败，失败原因:" + cdaDocumentContenValue.get("YZJGSM").toString());
                                        return result;
                                    }
                                }

                            }

                            //转base64编码
                            String base64Str = getBASE64(cdaDocumentStr);
                            if (base64Str == null || base64Str.equals("")) {
                                LOGGER.info("-->CDA文档转换Base64编码错误");
                                result.put("RESULT", "FAILD");
                                result.put("MSG", "将CDA文档生成Base64编码失败");

                                return result;
                            }

                            paramCDA.put("CONTENT", base64Str);
                            paramCDA.put("xmlContent", cdaDocumentStr);

                            //循环遍历查询出的个人新，并将其放入CDA缓存map中
                            for (String key : jbxxMap.keySet()) {
                                paramCDA.put(key, jbxxMap.get(key));
                            }

                            //填充CDA关键信息
                            /**
                             * 许多信息并不清楚本地库对应表结构和字段，待完善
                             */

                            //将cda信息保存到数据库
                            int returnRs = saveCDADOCBUFFER(paramCDA, dbDataSourceID);

                            if (returnRs != -1) {
                                LOGGER.info("--> CDA信息到表 IHE_CDA_DOC_BUFFER 成功");

                                result.put("RESULT", "OK");
                                return result;
                            } else {
                                LOGGER.info("--> CDA信息到表 IHE_CDA_DOC_BUFFER 失败");

                                result.put("RESULT", "FAILD");
                                result.put("MSG", "将CDA信息存入缓存表失败");
                                return result;
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e, e.fillInStackTrace());

            result.put("RESULT", "FAILD");
            result.put("MSG", "系统错误");
        }

        return result;
    }

    /**
     * 根据个人基本信息标识号，获取个人基本信息
     * 方法名称: queryGRJBXX
     *
     * @param
     * @return List<HashMap   <   String   ,   Object>>  返回类型说明<br/>
     * @throws <br/>
     * @author zq@winning.com.cn<br/>
     * 创建时间：2017-1-13/下午4:16:35<br/>
     */
    private HashMap<String, Object> queryGRJBXX(String grjbxxbsh, String dbDataSourceID) {
        try {

            String queryGRJBXXSQL = SQLConfigLoader.getSQLByID("IHE_QUERY_GRJBXX_FOR_INSERT");

            //LOGGER.info("-->查询个人信息语句SQL = " + queryGRJBXXSQL);

            List<HashMap<String, Object>> jbxxList = ServerSQLExecutorUtils.executeQueryOtherDB(queryGRJBXXSQL,
                    new Object[]{grjbxxbsh}, dbDataSourceID);

            if (jbxxList != null && jbxxList.size() > 0) {

                return jbxxList.get(0);
            }

        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 将生产的cda信息存入数据库中
     * 方法名称: saveCDADOCBUFFER
     *
     * @param
     * @return int  返回类型说明<br/>
     * @throws <br/>
     * @author lenovo@winning.com.cn<br/>
     * 创建时间：2017-1-13/下午4:30:08<br/>
     */
    private int saveCDADOCBUFFER(HashMap<String, Object> map, String dbDataSourceID) {
        try {
            //拼接插入SQL语句
            //填充信息
            Object[] params = new Object[map.size()];

            String insertSQL = "INSERT INTO IHE_CDA_DOC_BUFFER (";

            //参数个数标记
            int index = 0;

            //根据个人信息map表动态填充insert语句
            for (Entry<String, Object> entry : map.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();

                insertSQL += key + ",";

                params[index] = value;

                index++;

            }

            //添加创建时间createTime
            //			insertSQL += "CreateTime ";

            insertSQL += ") VALUES (";

            for (int i = 0; i < index; i++) {
                insertSQL += "?,";
            }

            /**

             if (dbDataSourceID.indexOf(Constans.DATA_SOURCE_ORACLE_TAG) > -1) {
             //添加创建时间createTime
             insertSQL += "sysdate ";
             } else {
             insertSQL += "getdate()";
             }
             */

            insertSQL += ")";

            LOGGER.info("-->新增SQL语句" + insertSQL);
            LOGGER.info("-->参数:" + params);

            ServerSQLExecutorUtils.execute(insertSQL, params, dbDataSourceID);

            LOGGER.info("-->新增成功");

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
        }

        return -1;
    }

    /**
     * 根据文档类型获取查询CDA类型SQL语句
     * 方法名称: getSQLByWDLX
     *
     * @param
     * @return String  返回类型说明<br/>
     * @throws <br/>
     * @author zhaqiang@winning.com.cn<br/>
     * 创建时间：2017-3-2/上午9:58:02<br/>
     */
    private String getQueryCDAInfoSQLByWDLX(String wdlx) {
        String sql = "";

        //个人基本健康信息档案
        if (wdlx.equals("01")) {
            sql = SQLConfigLoader.getSQLByID("IHE_QUERY_GR_JBXX");
        } else if (wdlx.equals("02")) {
            sql = SQLConfigLoader.getSQLByID("IHE_QUERY_TNB_CDA_INFO");
        } else if (wdlx.equals("03")) {
            sql = SQLConfigLoader.getSQLByID("IHE_QUERY_JKTJ_CDA_INFO");
        } else if (wdlx.equals("04")) {
            sql = SQLConfigLoader.getSQLByID("IHE_QUERY_ETJKJC_CDA_INFO");
        } else if (wdlx.equals("05")) {
            sql = SQLConfigLoader.getSQLByID("IHE_QUERY_XSRJTFS_CDA_INFO");
        }

        return sql;
    }

    private String getCdaTempFileByWDLX(String wdlx) {
        String fileName = "";

        //个人基本健康信息登记档案
        if (wdlx.equals("01")) {
            fileName = "cda_ehr_grjbjkxxdj_temp";
        } else if (wdlx.equals("02")) {
            fileName = "2型糖尿病随访记录";
        } else if (wdlx.equals("03")) {
            fileName = "成人健康体检";
        } else if (wdlx.equals("04")) {
            fileName = "儿童健康检查";
        } else if (wdlx.equals("05")) {
            fileName = "新生儿家庭访视";
        }

        return fileName;
    }

    private String getCdaTitleByWDLX(String wdlx) {
        String title = "";

        //个人基本健康信息登记档案
        if (wdlx.equals("01")) {
            title = "个人基本健康信息登记";
        } else if (wdlx.equals("02")) {
            title = "2型糖尿病随访记录";
        } else if (wdlx.equals("03")) {
            title = "成人健康体检";
        } else if (wdlx.equals("04")) {
            title = "儿童健康检查";
        } else if (wdlx.equals("05")) {
            title = "新生儿家庭访视";
        }

        return title;
    }

    /**
     * 根据ID查询详细健康档案信息
     * 方法名称: queryCDAInfoByID
     *
     * @param
     * @return JSONObject  返回类型说明<br/>
     * @throws <br/>
     * @author zhaqiang@winning.com.cn<br/>
     * 创建时间：2017-3-2/下午3:23:53<br/>
     */
    public JSONObject queryCDAInfoByID(String lsh) {
        JSONObject json = new JSONObject();

        try {
            String sql = SQLConfigLoader.getSQLByID("IHE_Client_QueryJKDA_ByID");

            //数据源
            String dataSourceID = getDBDataSouorceID(ZJG_JKDA_SERVICE_ID);

            json = iheDataDao.executSQLForJSONObject(sql, new Object[]{lsh}, dataSourceID);
        } catch (Exception e) {
            LOGGER.error(e, e.fillInStackTrace());
        }

        return json;
    }
}
